<style lang="less">
    @import "./list.less";
</style>

<template>
    <div class="agent-list-view">
        <Card>
            <span slot="title">代理商列表</span>
            <span slot="extra">
                <Button v-if="hasAddBtn" @click.prevent="addModal = !addModal" size="small" type="success" >
                    <Icon type="plus"></Icon>添加代理
                </Button>
                <Button size="small" type="success" @click="getAgentList"><Icon type="loop"></Icon>刷新列表</Button>
            </span>

            <Form label-position="left" label-width="80" inline>
                <Row>
                    <AgentSelect size="small" :agent-id.sync="search.parent_agent_id" @on-change="agentSelectChange"></AgentSelect>

                    <FormItem label-width="0">
                        <Input size="small" placeholder="账号/昵称/姓名" v-model="search.keyword"></Input>
                    </FormItem>

                    <FormItem label="审核状态：">
                        <Select size="small" v-model="search.audit_status" placeholder="审核状态">
                            <Option value="">全部</Option>
                            <Option value="wait_audit">待审核</Option>
                            <Option value="approved">已审核</Option>
                            <Option value="rejection">已拒绝</Option>
                        </Select>
                    </FormItem>
                    <FormItem label-width="0">
                        <Button type="success" :loading="searchLoading" size="small" icon="ios-search" @click="handleSearch" >检索</Button>
                    </FormItem>
                </Row>
                <Row>
                    <FormItem label="省市区：">
                        <Cascader style="margin-top:5px; width: 250px;" :data="regions" size="small" trigger="hover" v-model="regionSelected"></Cascader>
                    </FormItem>
                    <FormItem label="添加日期:">
                        <DatePicker size="small" @on-change="handleChangeDate" type="datetimerange" placeholder="请选择时间段" style="width:260px"></DatePicker>
                    </FormItem>
                </Row>
            </Form>
            <Row>
                <Col>
                    <Table border :loading="loading" height="450" :context="self" :columns="columns" :data="data"></Table>
                </Col>
            </Row>
            <Row style="padding: 5px 0">
                <Col>
                    <Page ref="Page"
                          :total="page.total"
                          :size="page.size"
                          :current.sync="page.current"
                          @on-change="handleChangePage"
                          @on-page-size-change="handleChangePageSize"
                          :page-size-opts="page.sizes" show-sizer show-elevator></Page>
                </Col>
            </Row>
        </Card>

        <Modal ref="addModal" v-model="addModal" :width="600">
            <p slot="header" style="text-align:center">
                <span>添加代理</span>
            </p>
            <div style="text-align:center">
                <addForm :root-node="this" :show.sync="addModal" :regions="regions" @on-change="handleAdded"></addForm>
            </div>
            <div slot="footer"></div>
        </Modal>

        <Modal ref="editModal" v-model="editModal" :width="600">
            <p slot="header" style="text-align:center">
                <span>修改代理信息</span>
            </p>
            <div style="text-align:center">
                <editForm :root-node="this" :show.sync="editModal" :edit-item.sync="editItem" :edit-item-index="editItemIndex"
                          :regions="regions" @on-change="handleEdited"></editForm>
            </div>
            <div slot="footer"></div>
        </Modal>

        <Modal ref="batchUpdateLadderPriceModal" :loading="batchUpdateLadderPriceModalLoading" @on-ok="handleBatchUpdateLadderPrice" v-model="batchUpdateLadderPriceModal" width="1040">
            <p slot="header" style="text-align:center">
                <span>修改[{{ batchUpdateLadderPriceData.agent_name }}代理]的设备阶梯定价</span>
            </p>
            <div style="text-align:center" class="ladder-price-card">
                <Form>
                    <Row :gutter="8">
                        <Col span="12">
                        <FormItem label="1级定价：">
                            <Input readonly type="number" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.one.min">
                                <span slot="append">到</span>
                            </Input>
                            <Input type="number" @on-change="batchUpdateLadderPriceData.ladder_price.two.min=batchUpdateLadderPriceData.ladder_price.one.max" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.one.max">
                                <span slot="append">分钟</span>
                            </Input>
                            <Input type="number" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.one.price">
                            <span slot="append" style="color:red;">元</span>
                            </Input>
                        </FormItem>
                        </Col>
                        <Col span="12">
                        <FormItem label="2级定价：">
                            <Input readonly type="number" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.two.min">
                                <span slot="append">到</span>
                            </Input>
                            <Input type="number" @on-change="batchUpdateLadderPriceData.ladder_price.three.min=batchUpdateLadderPriceData.ladder_price.two.max" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.two.max">
                                <span slot="append">分钟</span>
                            </Input>
                            <Input type="number" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.two.price">
                                <span slot="append" style="color:red;">元</span>
                            </Input>
                        </FormItem>
                        </Col>
                        <Col span="12">
                        <FormItem label="3级定价：">
                            <Input readonly type="number" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.three.min">
                                <span slot="append">到</span>
                            </Input>
                            <Input type="number" @on-change="batchUpdateLadderPriceData.ladder_price.four.min=batchUpdateLadderPriceData.ladder_price.three.max" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.three.max">
                                <span slot="append">分钟</span>
                            </Input>
                            <Input type="number" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.three.price">
                                <span slot="append" style="color:red;">元</span>
                            </Input>
                        </FormItem>
                        </Col>
                        <Col span="12" class="four-ladder-price">
                        <FormItem label="4级定价：">
                            <Input type="number" :number="true" maxlength="5" v-model="batchUpdateLadderPriceData.ladder_price.four.price">
                                <span slot="prepend">{{ batchUpdateLadderPriceData.ladder_price.four.min }}分钟后</span>
                                <span slot="append" style="color:red;">元</span>
                            </Input>
                        </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="24">
                            <div style="color: #f00; text-align: left;">* 此操作会批量设置代理名下的所有设备定价阶梯，请谨慎操作</div>
                        </Col>
                    </Row>
                </Form>
            </div>
        </Modal>
    </div>
</template>

<script>
    import util from '@/libs/util';
    import addForm from './add.vue';
    import editForm from './edit.vue';

    import AgentSelect from '../public/AgentSelect.vue';

    const viewButton = (vm, h, row, index) => {
        return h('a', {
                style: {
                    margin: '5px',
                },
                on: {
                    'click': (event) => {
                        vm.show(row)
                    }
                }
            }, '查看'
        );
    };

    const editButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    vm.edit(row, index)
                }
            }
        }, '编辑');
    };

    const batchUpdateLadderPriceButton = (vm, h, row, index) => {
        return h('div', {}, [
            h('a', {
                style: {
                    margin: '5px'

                },
                on: {
                    'click': (event) => {
                        vm.batchUpdateLadderPrice(row)
                    }
                }
            }, '设置设备阶梯价格')
        ]);
    };

    const auditRejectButton = (vm, h, row, index) => {
        return h('Poptip', {
            props: {
                confirm: true,
                title: '您确认该代理商审核不通过吗？',
                transfer: true
            },
            on: {
                'on-ok': () => {
                    vm.reject(row, index);
                }
            }
        }, [
            h('a', {
                style: {
                    margin: '5px',
                    color: 'red'
                }
            }, '拒绝通过')
        ]);
    };

    const auditPassButton = (vm, h, row, index) => {
        return h('Poptip', {
            props: {
                confirm: true,
                title: '您确认该代理商通过审核吗？',
                transfer: true
            },
            on: {
                'on-ok': () => {
                    vm.pass(row, index);
                }
            }
        }, [
            h('a', {
                style: {
                    margin: '5px',
                    color: 'green'
                }
            }, '通过审核')
        ]);
    };

    const toggleStatusButton = (vm, h, row, index) => {
        return h('Poptip', {
            props: {
                confirm: true,
                title: '您确定要修改该用户的账号状态吗?',
                transfer: true
            },
            on: {
                'on-ok': () => {
                    vm.updateStatus(row, index);
                }
            }
        }, [
            h('a', {
                style: {
                    margin: '5px',
                    color: row.is_effect ? 'red' : 'green'
                }
            }, row.is_effect ? '禁用' : '启用')
        ]);
    };

    export default {
        components: {
            addForm,
            editForm,
            AgentSelect
        },
        data () {
            return {
                self: this,
                addModal: false,
                editModal: false,
                editItem: {},
                editItemIndex: '',
                hasAddBtn: false,
                hasToggleStatusBtn: false,

                batchUpdateLadderPriceModal: false,
                batchUpdateLadderPriceModalLoading: true,
                batchUpdateLadderPriceData: {
                    agent_name: '',
                    agent_user_id: '',
                    ladder_price: {
                        one: {
                            min: 0,
                            max: 0,
                            price: 1
                        },
                        two: {
                            min: 0,
                            max: 0,
                            price: 2
                        },
                        three: {
                            min: 0,
                            max: 0,
                            price: 5
                        },
                        four: {
                            min: 0,
                            max: 999999,
                            price: 10
                        }
                    }
                },

                loading: false,

                page: {
                    total: 0,
                    current: 1,
                    size: 10,
                    sizes: [10, 30, 50, 100],
                },

                regions: [],
                regionSelected: [],
                regionLoading: false,

                searchLoading: false,
                search: {
                    parent_agent_id: '',
                    keyword: '',
                    created_at: '',
                    province_code: '',
                    city_code: '',
                    district_code: '',
                    audit_status: ''
                },

                columns: [
                    {
                        title: '账号',
                        key: 'name',
                        fixed: 'left',
                        width: 120
                    },
                    {
                        title: '姓名',
                        key: 'realname',
                        width: 120
                    },
                    {
                        title: '身份证号码',
                        key: 'identity_card',
                        width: 180
                    },
                    {
                        title: '性别',
                        key: 'sex_text',
                        width: 80
                    },
                    {
                        title: '上级代理',
                        key: 'parent_path',
                        width: 120
                    },
                    {
                        title: '级别',
                        key: 'agent_level_text',
                        width: 120
                    },
                    {
                        title: '分红比例(占上级收益的%)',
                        key: 'proration',
                        width: 220
                    },
                    {
                        title: '分红比例(占订单实际收益的%)',
                        key: 'real_proration',
                        width: 220
                    },
                    {
                        title: '账户余额',
                        key: 'balance',
                        width: 120
                    },
                    {
                        title: '地址',
                        key: 'full_address',
                        width: 250
                    },
                    {
                        title: '添加人',
                        key: 'operation_user_name',
                        align: 'center',
                        width: 120
                    },
                    {
                        title: '添加日期',
                        key: 'created_at',
                        width: 220
                    },
                    {
                        title: '账户状态',
                        key: 'is_effect',
                        width: 120
                    },
                    {
                        title: '审核状态',
                        key: 'audit_status_text',
                        width: 120
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 150
                    }

                ],
                data: []
            }
        },

        watch: {
            search: function (value) {
                console.log(value);
            },

            regionSelected: function (newVal) {
                this.search.province_code = newVal[0];
                this.search.city_code = newVal[1];
                this.search.district_code = newVal[2];
            },

            'batchUpdateLadderPriceData.ladder_price': function (ladder_price) {
                console.log(ladder_price);
            }
        },

        mounted () {
            this.getAgentList();
            this.getRegions();
        },

        created () {
            this.init();
            this.checkHasActionRole();
        },

        methods: {
            checkHasActionRole ()  {
                let userRoles = this.$store.state.user.user.roles_name || [];
                if (util.anyInOf(userRoles, ['admin', 'system', 'agent'])) {
                    if (util.oneOf('agent', this.$store.state.user.user.roles_name)) {
                        if (this.$store.state.user.user.extension.agent_level > 2) {
                            this.hasAddBtn = false;
                            this.hasToggleStatusBtn = false;
                        } else {
                            this.hasAddBtn = true;
                            this.hasToggleStatusBtn = true;
                        }
                    } else {
                        this.hasAddBtn = true;
                        this.hasToggleStatusBtn = true;
                    }
                }
            },

            init () {
                let vm = this;

                this.columns.forEach(item => {
                    if (item.key == 'action') {
                        item.render = (h, param) => {
                            const buttons = [];
                            buttons.push(viewButton(vm, h, param.row, param.index));

                            let userRoles = this.$store.state.user.user.roles_name || [];
                            if (util.anyInOf(userRoles, ['admin', 'system'])) {
                                buttons.push(editButton(vm, h, param.row, param.index));
                                if (this.hasToggleStatusBtn) {
                                    buttons.push(toggleStatusButton(vm, h, param.row, param.index));
                                }
                                if (param.row.extension.audit_status !== 'approved') {
                                    buttons.push(auditPassButton(vm, h, param.row, param.index));
                                    if (param.row.extension.audit_status !== 'rejection') {
                                        buttons.push(auditRejectButton(vm, h, param.row, param.index));
                                    }
                                }

                                if (param.row.extension.agent_level == 3) {
                                    buttons.push(batchUpdateLadderPriceButton(vm, h, param.row, param.index));
                                }
                            }

                            if (util.anyInOf(userRoles, ['agent'])) {
                                if (param.row.parent_id === this.$store.state.user.user.id) {
                                    //buttons.push(editButton(vm, h, param.row, param.index));
                                }
                            }

                            return buttons;
                        };
                    }

                    if (item.key == 'is_effect') {
                        item.render = (h, param) => {
                            if (param.row.is_effect == 1) {
                                return h('span', {
                                    style: {
                                        color: 'green'
                                    }
                                }, '已启用');
                            } else {
                                return h('span', {
                                    style: {
                                        color: 'red'
                                    }
                                }, '已禁用');
                            }
                        };
                    }

                    if (item.key == 'agent_level_text') {
                        item.render = (h, param) => {
                            return h('span', {}, param.row.extension.agent_level_text);
                        };
                    }

                    if (item.key == 'balance') {
                        item.render = (h, param) => {
                            return h('span', {}, param.row.balance + ' 元');
                        };
                    }

                    if (item.key == 'proration') {
                        item.render = (h, param) => {
                            return h('span', {}, param.row.extension.proration + '%');
                        };
                    }

                    if (item.key == 'operation_user_name') {
                        item.render = (h, param) => {
                            return h('span', {}, param.row.extension.operation_user_name);
                        };
                    }

                    if (item.key == 'audit_status_text') {
                        item.render = (h, param) => {
                            return h('span', {}, param.row.extension.audit_status_text);
                        };
                    }

                    if (item.key == 'real_proration') {
                        item.render = (h, param) => {
                            return h('span', {}, this.realProration(param.row, param.row.extension.proration) + '%');
                        };
                    }
                });
            },

            getAgentList () {
                this.loading = true;

                let params = {
                    page: this.page.current,
                };
                params = Object.assign(params, this.search);

                util.api().get(`/admin/api/agents`, {
                    params,
                    headers: {
                        pageSize: this.page.size,
                    }
                }).then((resp) => {
                    this.$Message.destroy();
                    if (resp.data.status == true) {
                        this.data = resp.data.data;
                        this.page.total = resp.data.meta.total;
                        this.page.current = resp.data.meta.current_page;
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                    this.loading = false;
                }).catch((e) => {
                    util.handleApiException(e, this, '获取代理列表失败');
                })
            },

            handleAdded (row) {
                this.data.push(row);
            },

            handleEdited(row) {
               this.getAgentList();
            },

            handleChangePage (page) {
                this.page.current = page;
                this.getAgentList();
            },

            handleChangePageSize (size) {
                this.page.size = size;
                this.getAgentList();
            },

            updateStatus (row, index) {
                let newStatus = row.is_effect == 1 ? 0 : 1;

                util.api().patch(`/admin/api/agents/${row.id}/status/${newStatus}`).then((resp) => {
                    if (resp.data.status == true) {
                        this.data[index].is_effect = newStatus;
                        this.$Message.success(resp.data.message);
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                }).catch((e) => {
                    util.handleApiException(e, this, '修改代理账号状态失败');
                });
            },

            handleSearch () {
                this.page.current = 1;
                this.getAgentList();
            },

            handleChangeDate (date) {
                if (date[1] != undefined) {
                    this.search.created_at = date;
                } else {
                    this.search.created_at = [];
                }
            },

            getRegions () {
                this.regionLoading = true;
                util.ajax.get('/api/regions/format').then((resp) => {
                    const formatTree = (arr) => {
                        let regions = [];
                        for (let i in arr) {
                            let node = {};
                            node.value = arr[i].code;
                            node.label = arr[i].name;
                            node.disabled = arr[i].disabled;
                            if (arr[i].hasOwnProperty('children')) {
                                node.children = formatTree(arr[i].children);
                            }

                            regions.push(node);
                        }
                        return regions;
                    };

                    this.regions = formatTree(resp.data.data);
                    this.regionLoading = false;
                }).catch((e) => {
                    this.regionLoading = false;
                    util.handleApiException(e, this, '获取省市区数据失败');
                })
            },

            pass(row, index) {
                util.api().patch(`/admin/api/agents/${row.id}/pass`).then((resp) => {
                    if (resp.data.status == true) {
                        this.data[index].extension.audit_status = resp.data.data.audit_status;
                        this.data[index].extension.audit_status_text = resp.data.data.audit_status_text;
                        this.$Notice.success({ title: resp.data.message });
                    } else {
                        this.$Notice.error({ title: resp.data.message });
                    }
                }).catch((e) => {
                    util.handleApiException(e, this, '代理商审核失败');
                });
            },

            reject(row, index) {
                util.api().patch(`/admin/api/agents/${row.id}/reject`).then((resp) => {
                    if (resp.data.status == true) {
                        this.data[index].extension.audit_status = resp.data.data.audit_status;
                        this.data[index].extension.audit_status_text = resp.data.data.audit_status_text;
                        this.$Notice.success({ title: resp.data.message });
                    } else {
                        this.$Notice.error({ title: resp.data.message });
                    }
                }).catch((e) => {
                    util.handleApiException(e, this, '代理商审核失败');
                });
            },

            edit (row, index) {
                this.editModal = true;
                this.editItem = row;
                this.editItemIndex = index;
            },

            show(row) {
                let proration_str = row.extension.proration + '%; ';

                this.$Modal.info({
                    title: '代理信息',
                    width: 600,
                    content: `ID：${row.id}<br>账号：${row.name}<br>真实姓名：${row.realname}<br>昵称：${row.nickname}<br>`
                        + `代理级别：${row.extension.agent_level_text}<br>分红比例：${proration_str}<br>`
                        + `添加时间：${row.created_at}<br>更新时间：${row.updated_at}`
                });
            },

            batchUpdateLadderPrice (row) {
                this.batchUpdateLadderPriceModal = true;
                this.batchUpdateLadderPriceData = {
                    agent_name: row.name,
                    agent_user_id: row.id,
                    ladder_price: {
                        one: {
                            min: 0,
                            max: 0,
                            price: 1
                        },
                        two: {
                            min: 0,
                            max: 0,
                            price: 2
                        },
                        three: {
                            min: 0,
                            max: 0,
                            price: 5
                        },
                        four: {
                            min: 0,
                            max: 999999,
                            price: 10
                        }
                    }
                };
            },

            handleBatchUpdateLadderPrice () {
                if (this.validatePriceRange()) {
                    util.api().patch(`/admin/api/devices/batch/ladder_price/${this.batchUpdateLadderPriceData.agent_user_id}`, { ladder_price: this.batchUpdateLadderPriceData.ladder_price}).then((resp) => {
                        if (resp.data.status == true) {
                            this.$Notice.success({ title: resp.data.message });
                            this.batchUpdateLadderPriceModal = false;
                        } else {
                            this.$Notice.error({ title: resp.data.message });
                            this.batchUpdateLadderPriceModal = true;
                        }
                    }).catch((e) => {
                        util.handleApiException(e, this, '设置代理商设备阶梯定价失败');
                        this.batchUpdateLadderPriceModalLoading = false;
                    });
                }
            },

            agentSelectChange (value) {
                console.log(value);
                this.search.parent_agent_id = value;
            },

            validatePriceRange() {
                const ladder_price = this.batchUpdateLadderPriceData.ladder_price;
                if (ladder_price.one.min != 0) {
                    this.$Notice.error({ title: '设备定价阶梯必须从0分钟开始计算'});
                    return false;
                } else if (ladder_price.one.min >= ladder_price.one.max) {
                    this.$Notice.error({ title: '1级定价阶梯时间范围填写错误，开始时间必须小于结束时间'});
                    return false;
                } else if (ladder_price.two.min != ladder_price.one.max) {
                    this.$Notice.error({ title: '2级定价阶梯必须从1级定价结束时间开始'});
                    return false;
                } else if (ladder_price.two.min >= ladder_price.two.max) {
                    this.$Notice.error({ title: '2级定价阶梯时间范围填写错误，开始时间必须小于结束时间'});
                    return false;
                } else if (ladder_price.three.min != ladder_price.two.max) {
                    this.$Notice.error({ title: '3级定价阶梯必须从2级定价结束时间开始'});
                    return false;
                } else if (ladder_price.three.min >= ladder_price.three.max) {
                    this.$Notice.error({ title: '3级定价阶梯时间范围填写错误，开始时间必须小于结束时间'});
                    return false;
                } else if (ladder_price.four.min != ladder_price.three.max) {
                    this.$Notice.error({ title: '4级定价阶梯必须从3级定价结束时间开始'});
                    return false;
                }

                return true;
            },

            realProration(user, proration) {
                if (user.extension.agent_level == 1) {
                    return proration;
                } else if (user.extension.agent_level == 2){
                    let _proration = user.extension.parent.extension.proration * proration / 100;
                    return _proration.toFixed(2);
                } else {
                    let agent_v2_ratio = user.extension.parent.extension.parent.extension.proration * user.extension.parent.extension.proration / 100;
                    let _proration = agent_v2_ratio * proration / 100;
                    return _proration.toFixed(2);
                }
            }
        }
    };
</script>
